using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using mojoPortal.Data;

public partial class MyCustomModules_UpdateDocStatus : System.Web.UI.Page
{
    string conn = System.Configuration.ConfigurationManager.AppSettings.Get("MSSQLConnectionString");
    DataSet ds = new DataSet();
    string strFullName = string.Empty;
    string strTo = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Get status information
            ds = mojoPortal.Data.SqlHelper.ExecuteDataset(
                conn, CommandType.StoredProcedure, "usp_GetStatusUpdatesAudit",
                new System.Data.SqlClient.SqlParameter("@DocID", Request.QueryString["DocID"]));

            grdStatus.DataSource = ds.Tables[0];
            grdStatus.DataBind();

            if ((!HttpContext.Current.User.IsInRole("Content Administrators") &&
                !HttpContext.Current.User.IsInRole("Admins")) || Request.QueryString["fromMail"] == null  || Request.QueryString["fromMail"] == "yes")
            {
                btnAddNewStatus.Visible = false;
                btnAddNewStatusClose.Visible = false;
                lnlHome.Visible = true;
            }
            else
                lnlHome.Visible = false;
        }
        lnlHome.NavigateUrl=System.Configuration.ConfigurationManager.AppSettings.Get("URLSpecifiedInMail");
    }

    protected bool GetCompletedStatus(object value)
    {
        if ((int)value == 0)
            return false;
        else
            return true;
    }

    protected bool GetMarkAsRead(object valRead)
    {
        if (!HttpContext.Current.User.IsInRole("Content Administrators") && !HttpContext.Current.User.IsInRole("Admins"))
            return false;
        
        if ((bool)valRead)
            return false;
        else
            return true;
    }

    protected string GetFormatedTime(object value)
    {
         DateTime dt;

        if (DateTime.TryParse( Convert.ToString( value),out dt))
        {
          
            return dt.ToString("dd-MMM-yyyy HH:mm:ss ");
        }
        else
            return "";

    }

    protected bool GetCommentEnabled(object value)
    {
        if (!HttpContext.Current.User.IsInRole("Content Administrators") && !HttpContext.Current.User.IsInRole("Admins"))
            return false;
        return !(bool)value;
    }

    protected void AddNewStatusClick(object sender, EventArgs e)
    {

        if (((Button)sender).Text.ToLower() == "close")
        {
            if (Request.QueryString["fromMail"] == null || Request.QueryString["fromMail"] == "yes")
                RegisterStartupScript("CloseWindow", "<script language='javascript'>window.close();</script>");
            else
                RegisterStartupScript("CloseWindow", "<script language='javascript'>closeParent();</script>");
            return;
        }

        Control cntrl;
        Control cntrl2;
        int auditID;
        int statusID;

        // Loop through all rows of grid and find out values
        foreach (GridViewRow grv in grdStatus.Rows)
        {
         
            CheckBox chk = (CheckBox)grv.Cells[0].FindControl("chkComplete");
            if (chk.Enabled & chk.Checked )
            {
               if ( !Int32.TryParse(grdStatus.DataKeys[grv.RowIndex].Values[0].ToString(), out auditID ))
               {
                   auditID = 0;
               }

               statusID = (int)grdStatus.DataKeys[grv.RowIndex].Values[1];
                cntrl2 = grv.Cells[0].FindControl("txtComments");
                if (cntrl2 != null)
                {
                    if (AddNewStatusUpdate(auditID, statusID, ((TextBox)cntrl2).Text) > 0)
                    {
                        //Send mail
                        //SendConfirmationMail();
                    }
                }
               
            }
   
        }

        //Send mail
        SendConfirmationMail();

        if (((Button )sender).Text.ToLower() == "save")
        {
            //Reload grid view in order to show refreshed data 
            ds = mojoPortal.Data.SqlHelper.ExecuteDataset(
                conn, CommandType.StoredProcedure, "usp_GetStatusUpdatesAudit",
                new System.Data.SqlClient.SqlParameter("@DocID", Request.QueryString["DocID"]));
            grdStatus.DataSource = ds.Tables[0];
            grdStatus.DataBind();
            RegisterStartupScript("RefreshParent", "<script language='javascript'>refreshParent();</script>");
        }
        else
        {
            RegisterStartupScript("RefreshParent", "<script language='javascript'>closeParent();</script>");
        }

    }
    protected void SendConfirmationMail()
    {
        // FullName - get from docid
        // Send to - get from docid
        // Updated By - httpcontext
        // DocumentName - from docid
        // Stauts Message - from grid
        // StatusComments - from grid
        // StatusDateTime - datetime.now
        // Get NEW URL for link to status page - currentpage ? docid&userID
        // 
        string strTo = String.Empty;
        string strCC = String.Empty;

        MailMerge msg = new MailMerge("StatusUpdated");
        msg.StatusDateTime = DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");

        System.Data.SqlClient.SqlDataReader dr = mojoPortal.Data.SqlHelper.ExecuteReader
           (conn, CommandType.StoredProcedure, "usp_GetDocumentProperties",
           new System.Data.SqlClient.SqlParameter("@DocID", Request.QueryString["DocID"]));
        if (dr.HasRows)
        {
            dr.Read();
            msg.FullName = dr["DocOwner"].ToString();
            msg.UpdatedBy = dr["UpdatedBy"].ToString();
            msg.DocumentPath = dr["FilePath"].ToString();
            msg.DocumentName = Common.GetActualFileName(dr["FilePath"].ToString());
            msg.StatusMessage = dr["Status"].ToString();
            msg.StatusComments = dr["Comments"].ToString();
            msg.CustomURL = System.Configuration.ConfigurationManager.AppSettings.Get("URLSpecifiedInMail") + "/" + 
                System.Configuration.ConfigurationManager.AppSettings.Get("ShowRecieveDocLink") + 
                "?DocID=" + Request.QueryString["DocID"] + "&userid=" + dr["DocOwnerGuid"].ToString() + "&fromMail=yes";
            strTo = dr["DocOwnerEmail"].ToString();
            strCC = dr["DocParentEmail"].ToString();
        }
        dr.Close();

        msg.GetMailDetails();
        Common.SendMailMessage(strTo, strTo == strCC ? "" : strCC, System.Configuration.ConfigurationManager.AppSettings.Get("SMTPTo"), msg.Subject, msg.Body);
        //MailHelper.SendMailMessage(strTo, strTo == strCC ? "" : strCC, System.Configuration.ConfigurationManager.AppSettings.Get("SMTPTo"), msg);
    }


    protected int AddNewStatusUpdate(int auditID, int statusID, string sComments)
    {
        mojoPortal.Data.SqlParameterHelper sph = new mojoPortal.Data.SqlParameterHelper(conn, "usp_UpdateStatus", CommandType.StoredProcedure, 5);
        sph.DefineSqlParameter("@AuditID", SqlDbType.Int, ParameterDirection.Input, auditID);
        sph.DefineSqlParameter("@DocID", SqlDbType.Int, ParameterDirection.Input, Int32.Parse( Request.QueryString["DocID"].ToString()));
        sph.DefineSqlParameter("@UserID", SqlDbType.UniqueIdentifier, ParameterDirection.Input, new Guid(Request.QueryString["UserID"]));
        sph.DefineSqlParameter("@StatusID", SqlDbType.Int , ParameterDirection.Input, statusID);
        sph.DefineSqlParameter("@Comments", SqlDbType.NVarChar, 2000, ParameterDirection.Input, sComments);

        int result = Convert.ToInt32(sph.ExecuteNonQuery());
        if (result == -1)
        {
            lblMessage.Text = "Error occured";
        }
        else if (result > 0)
            lblMessage.Text = "";
        else
            lblMessage.Text = "Error occured";

        return result;
       
    }
    
}
